package ace.cmp.data.methodname.method.name.sql.entity.resolver.impl.property;

import ace.cmp.data.methodname.method.name.sql.core.enums.SqlCommandTypeEnum;
import ace.cmp.data.methodname.method.name.sql.entity.model.EntityMapping;
import ace.cmp.data.methodname.method.name.sql.entity.model.EntityPropertyMapping;
import ace.cmp.data.methodname.method.name.sql.entity.resolver.property.EntityMethodNameToQueryPropertyResolver;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @author caspar
 * @date 2023/2/18 11:17 从方法解析实体查询元数据, 直接返回实体所有属性
 */
public class SelectQueryPropertyEntityResolverChain
    implements EntityMethodNameToQueryPropertyResolver {
  private final List<AbstractSelectQueryPropertyResolver> queryPropertyResolvers;
  private final SqlCommandTypeEnum sqlCommandType;
  private final Method method;
  private final EntityMapping entityMapping;

  public SelectQueryPropertyEntityResolverChain(
      SqlCommandTypeEnum sqlCommandType, Method method, EntityMapping entityMapping) {
    this.sqlCommandType = sqlCommandType;
    this.entityMapping = entityMapping;
    this.method = method;
    this.queryPropertyResolvers =
        Arrays.asList(
            new SelectQueryPropertyLastInputParameterResolverImpl(
                sqlCommandType, method, entityMapping),
            new SelectQueryPropertyOutParameterFirstGenericResolverImpl(
                sqlCommandType, method, entityMapping),
            new SelectQueryPropertyEntityResolverImpl(sqlCommandType, method, entityMapping));
  }

  @Override
  public List<EntityPropertyMapping> getProperties() {
    for (EntityMethodNameToQueryPropertyResolver queryPropertyResolver :
        this.queryPropertyResolvers) {
      List<EntityPropertyMapping> propertyMappings = queryPropertyResolver.getProperties();
      if (propertyMappings != null && propertyMappings.size() > 0) {
        return propertyMappings;
      }
    }

    throw new RuntimeException(
        String.format(
            "[%s] method [%s] can't resolve entity property mapping",
            this.entityMapping.getEntityClass().getName(), this.method.getName()));
  }

  @Override
  public Boolean getSupport() {
    return SqlCommandTypeEnum.SELECT.equals(this.sqlCommandType);
  }
}
